package com.ruoyi.water.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.water.domain.Homepage;
import com.ruoyi.water.service.IHomepageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 首页水相关Controller
 * 处理与t_homepage_jh_water表相关的HTTP请求
 */
@RestController
@RequestMapping("/water/homepage")
public class HomepageController extends BaseController {

    @Autowired
    private IHomepageService homepageService;

    /**
     * 新增首页水数据
     */
    @PostMapping
    public AjaxResult add(@RequestBody Homepage homepage) {
        return toAjax(homepageService.save(homepage) ? 1 : 0);
    }

    /**
     * 根据ID查询首页水数据
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable Integer id) {
        return AjaxResult.success(homepageService.getById(id));
    }

    /**
     * 查询首页水数据列表
     */
    @GetMapping("/list")
    public AjaxResult list(Homepage homepage) {
        // 构建查询条件
        LambdaQueryWrapper<Homepage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(homepage.getValueType() != null, Homepage::getValueType, homepage.getValueType());
        queryWrapper.like(homepage.getKey() != null, Homepage::getKey, homepage.getKey());
        queryWrapper.like(homepage.getValueCode() != null, Homepage::getValueCode, homepage.getValueCode());

        List<Homepage> list = homepageService.list(queryWrapper);
        return AjaxResult.success(list);
    }

    /**
     * 修改首页水数据
     */
    @PutMapping
    public AjaxResult edit(@RequestBody Homepage homepage) {
        return toAjax(homepageService.updateById(homepage) ? 1 : 0);
    }

    /**
     * 删除首页水数据
     */
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Integer id) {
        return toAjax(homepageService.removeById(id) ? 1 : 0);
    }

    /**
     * 新增接口：计算用水趋势并保存
     */
    @PostMapping("/calculateHomepage")
    public AjaxResult calculateHomepage() {
        try {
            homepageService.calculateHomepage();
            return AjaxResult.success("用水趋势计算完成");
        } catch (Exception e) {
            return AjaxResult.error("计算失败：" + e.getMessage());
        }
    }
}